import React from 'react'

export default function cat() {
  const [list,setList]=React.useState([
    {name:"橘子",price:5,checked:false,num:1,id:0},
    {name:"西瓜",price:7,checked:false,num:1,id:1},
    {name:"苹果",price:10,checked:false,num:1,id:2},
    {name:"枇杷",price:15,checked:false,num:1,id:3},
  ])

  function changeCheck(id:number){
    for (const item of list) {
        if(item.id==id){
            item.checked=!item.checked
            break

        }
        
    }
    setList([...list])
  }
  function changnum(id:number,n:-1|1){
    for (const item of list) {
      if(item.id==id){
          item.num+=n
          break

      }
  }
  setList([...list])
  }

  function del(id:number){

   const newList= list.filter(item=>item.id !=id)

   setList(newList)
  }

    const total=React.useMemo(()=>{
    let t=0
    list.filter(item=>item.checked).forEach(item=>{
       t+=item.price*item.num
    })
    return t
  },[list])


  return (
    {
      list,
      changeCheck,
      changnum,
      del,
      total

    }
  )
}

